package com.bite.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.bite.common.core.constants.Constants;
import com.bite.common.core.constants.HttpConstants;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.common.security.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

//拦截器需要和配置文件使用，就是对拦截器进行注册
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;
    /**
     * 我们从nacos中获取secret得值，获取的时候并不是说写在security下，就在nacos的配置文件的secrity下拿值
     * 而是说，哪个容器装配了这个bean对象，就从哪个容器中取值，比如说未来这里的代码会被system项目调用，
     * 那次是secret的值也是从system的配置文件中获取
    **/
    @Value("${jwt.secret}")
    private String secret;
    //拦截器和微服务在同一个线程中
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        if(StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
              //去除前缀
            token = token.replaceFirst(HttpConstants.PREFIX,"");
        }
        Long userId = tokenService.getUserId(token,secret);
        ThreadLocalUtil.set(Constants.USER_ID,userId);
        tokenService.extendToken(token,secret);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
